﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraCharts;
using System.Drawing.Drawing2D;

namespace MesProjectWinform.BasicData.基础实现.chanpin
{
    public partial class daping : DevExpress.XtraEditors.XtraForm
    {
        // 定义数据集合
        private List<double> productionData = new List<double>();
        private Random random = new Random();
        private int dataCount = 0;
        private string selectedProductType = "四轴无人机";
        private Dictionary<string, int> productDistribution = new Dictionary<string, int>
        {
            { "四轴无人机", 0 },
            { "六轴无人机", 0 },
            { "固定翼无人机", 0 },
            { "垂直起降无人机", 0 }
        };
        
        // 定义科技感颜色
        private Color primaryColor = Color.FromArgb(0, 120, 212);      // 主色调
        private Color accentColor = Color.FromArgb(0, 210, 255);       // 强调色
        private Color darkColor = Color.FromArgb(20, 30, 48);          // 暗色调
        private Color lightColor = Color.FromArgb(240, 245, 255);      // 亮色调
        private Color backgroundColor = Color.FromArgb(28, 35, 65);    // 背景色
        private Color panelColor = Color.FromArgb(35, 45, 75);         // 面板色

        public daping()
        {
            InitializeComponent();
            
            // 设置窗体属性以便更好地嵌入
            this.FormBorderStyle = FormBorderStyle.None;
            this.Dock = DockStyle.Fill;
            this.AutoScroll = true;
        }

        private void daping_Load(object sender, EventArgs e)
        {
            try
            {
                // 初始化界面
                InitializeUI();
                
                // 设置下拉框默认选项
                comboBoxEdit1.SelectedIndex = 0;
                
                // 初始化数据
                InitializeData();
                
                // 创建图表
                CreateCharts();
                
                // 默认禁用停止按钮
                simpleButton2.Enabled = false;
                
                // 自动启动数据更新
                simpleButton1_Click(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化界面时出错: " + ex.Message);
            }
        }

        private void InitializeUI()
        {
            // 移除窗体设置，因为现在是嵌入模式
            // this.FormBorderStyle = FormBorderStyle.FixedSingle;
            // this.MaximizeBox = false;
            // this.MinimizeBox = true;
            // this.StartPosition = FormStartPosition.CenterScreen;
            
            // 设置窗体背景色
            this.BackColor = backgroundColor;
            
            // 设置标题颜色和样式
            foreach (Control control in this.Controls)
            {
                if (control is Label)
                {
                    Label label = (Label)control;
                    label.ForeColor = accentColor;
                    label.Font = new Font("微软雅黑", label.Font.Size, FontStyle.Bold);
                }
            }
            
            // 设置面板圆角和颜色
            ApplyPanelStyles(chartPanel1);
            ApplyPanelStyles(chartPanel2);
            ApplyPanelStyles(gaugePanel1);
            
            // 设置按钮样式
            ApplyButtonStyles(simpleButton1);
            ApplyButtonStyles(simpleButton2);
            
            // 设置下拉框样式
            comboBoxEdit1.Properties.AppearanceDropDown.BackColor = panelColor;
            comboBoxEdit1.Properties.AppearanceDropDown.ForeColor = lightColor;
            comboBoxEdit1.Properties.Appearance.BackColor = panelColor;
            comboBoxEdit1.Properties.Appearance.ForeColor = lightColor;
            comboBoxEdit1.Properties.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.Simple;
        }
        
        private void ApplyPanelStyles(Panel panel)
        {
            // 创建圆角面板
            panel.BackColor = panelColor;
            panel.Paint += (sender, e) =>
            {
                // 创建圆角区域
                int radius = 15;
                Rectangle rect = new Rectangle(0, 0, panel.Width - 1, panel.Height - 1);
                GraphicsPath path = new GraphicsPath();
                path.AddArc(rect.X, rect.Y, radius * 2, radius * 2, 180, 90);
                path.AddArc(rect.X + rect.Width - radius * 2, rect.Y, radius * 2, radius * 2, 270, 90);
                path.AddArc(rect.X + rect.Width - radius * 2, rect.Y + rect.Height - radius * 2, radius * 2, radius * 2, 0, 90);
                path.AddArc(rect.X, rect.Y + rect.Height - radius * 2, radius * 2, radius * 2, 90, 90);
                path.CloseAllFigures();
                
                // 绘制圆角和边框
                e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
                using (SolidBrush brush = new SolidBrush(panelColor))
                {
                    e.Graphics.FillPath(brush, path);
                }
                using (Pen pen = new Pen(accentColor, 1))
                {
                    e.Graphics.DrawPath(pen, path);
                }
                
                // 绘制科技感装饰线
                using (Pen accentPen = new Pen(accentColor, 2))
                {
                    e.Graphics.DrawLine(accentPen, rect.X + 10, rect.Y + 35, rect.X + 50, rect.Y + 35);
                }
            };
        }
        
        private void ApplyButtonStyles(SimpleButton button)
        {
            // 设置按钮样式
            button.Appearance.BackColor = primaryColor;
            button.Appearance.ForeColor = Color.White;
            button.Appearance.Options.UseBackColor = true;
            button.Appearance.Options.UseForeColor = true;
            button.Appearance.BorderColor = accentColor;
            button.Appearance.Options.UseBorderColor = true;
            
            // 设置按钮圆角
            button.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Flat;
            button.LookAndFeel.UseDefaultLookAndFeel = false;
            
            // 设置鼠标悬停效果
            button.MouseEnter += (sender, e) => 
            {
                button.Appearance.BackColor = accentColor;
            };
            
            button.MouseLeave += (sender, e) => 
            {
                button.Appearance.BackColor = primaryColor;
            };
        }

        private void InitializeData()
        {
            // 初始化产品分布数据
            foreach (var key in productDistribution.Keys.ToList())
            {
                productDistribution[key] = random.Next(10, 50);
            }
            
            // 初始化生产数据
            for (int i = 0; i < 10; i++)
            {
                productionData.Add(Math.Round(random.NextDouble() * 100, 2));
            }
        }
        
        private void CreateCharts()
        {
            try
            {
                // 创建折线图
                CreateLineChart();
                
                // 创建饼图
                CreatePieChart();
                
                // 创建柱状图
                CreateBarChart();
            }
            catch (Exception ex)
            {
                MessageBox.Show("创建图表时出错: " + ex.Message);
            }
        }
        
        private void CreateLineChart()
        {
            // 创建折线图面板
            Panel lineChartPanel = new Panel();
            lineChartPanel.Dock = DockStyle.Fill;
            lineChartPanel.BackColor = Color.Transparent;
            
            // 添加标题
            Label titleLabel = new Label();
            titleLabel.Text = "实时生产数据趋势";
            titleLabel.Font = new Font("微软雅黑", 12, FontStyle.Bold);
            titleLabel.ForeColor = accentColor;
            titleLabel.AutoSize = true;
            titleLabel.Location = new Point(10, 10);
            
            // 创建图表区域
            Panel chartArea = new Panel();
            chartArea.Dock = DockStyle.Bottom;
            chartArea.Height = chartPanel1.Height - 40;
            chartArea.BackColor = Color.Transparent;
            chartArea.Paint += (sender, e) => DrawLineChart(e.Graphics, chartArea.ClientRectangle);
            
            // 添加控件到面板
            lineChartPanel.Controls.Add(titleLabel);
            lineChartPanel.Controls.Add(chartArea);
            
            // 添加到主面板
            chartPanel1.Controls.Add(lineChartPanel);
        }
        
        private void DrawLineChart(Graphics g, Rectangle bounds)
        {
            if (productionData.Count == 0) return;
            
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            
            // 计算坐标
            float maxValue = (float)productionData.Max() * 1.2f;
            float minValue = 0;
            int padding = 30;
            int leftPadding = 40;
            int bottomPadding = 30;
            
            float graphWidth = bounds.Width - leftPadding - padding;
            float graphHeight = bounds.Height - padding - bottomPadding;
            
            // 绘制坐标轴
            using (Pen axisPen = new Pen(Color.FromArgb(150, 150, 180), 1))
            {
                // Y轴
                g.DrawLine(axisPen, 
                    new Point(bounds.Left + leftPadding, bounds.Top + padding),
                    new Point(bounds.Left + leftPadding, bounds.Bottom - bottomPadding));
                    
                // X轴
                g.DrawLine(axisPen,
                    new Point(bounds.Left + leftPadding, bounds.Bottom - bottomPadding),
                    new Point(bounds.Right - padding, bounds.Bottom - bottomPadding));
            }
            
            // 绘制网格线
            using (Pen gridPen = new Pen(Color.FromArgb(80, 80, 120), 1))
            {
                gridPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                
                // 水平网格线
                int ySteps = 5;
                for (int i = 0; i <= ySteps; i++)
                {
                    int y = bounds.Bottom - bottomPadding - (int)(i * graphHeight / ySteps);
                    g.DrawLine(gridPen,
                        new Point(bounds.Left + leftPadding, y),
                        new Point(bounds.Right - padding, y));
                        
                    // 绘制Y轴刻度
                    float value = minValue + (maxValue - minValue) * i / ySteps;
                    string valueText = value.ToString("F1");
                    SizeF textSize = g.MeasureString(valueText, new Font("Arial", 8));
                    g.DrawString(valueText, new Font("Arial", 8), new SolidBrush(Color.FromArgb(200, 200, 220)),
                        new PointF(bounds.Left + leftPadding - textSize.Width - 5, y - textSize.Height / 2));
                }
            }
            
            // 计算每个点的坐标
            PointF[] points = new PointF[productionData.Count];
            float xStep = graphWidth / (productionData.Count - 1);
            
            for (int i = 0; i < productionData.Count; i++)
            {
                float x = bounds.Left + leftPadding + i * xStep;
                float y = bounds.Bottom - bottomPadding - (float)((productionData[i] - minValue) / (maxValue - minValue) * graphHeight);
                points[i] = new PointF(x, y);
                
                // 绘制X轴刻度
                if (i % 2 == 0 || i == productionData.Count - 1)
                {
                    string xLabel = (i + 1).ToString();
                    SizeF textSize = g.MeasureString(xLabel, new Font("Arial", 8));
                    g.DrawString(xLabel, new Font("Arial", 8), new SolidBrush(Color.FromArgb(200, 200, 220)),
                        new PointF(x - textSize.Width / 2, bounds.Bottom - bottomPadding + 5));
                }
            }
            
            // 创建渐变画笔
            using (LinearGradientBrush lineBrush = new LinearGradientBrush(
                new Point(bounds.Left, bounds.Top),
                new Point(bounds.Right, bounds.Top),
                accentColor,
                primaryColor))
            {
                // 绘制线条
                using (Pen linePen = new Pen(lineBrush, 2))
                {
                    g.DrawLines(linePen, points);
                }
            }
            
            // 绘制数据点
            using (SolidBrush pointBrush = new SolidBrush(accentColor))
            {
                foreach (PointF point in points)
                {
                    g.FillEllipse(pointBrush, point.X - 3, point.Y - 3, 6, 6);
                    // 添加发光效果
                    using (GraphicsPath path = new GraphicsPath())
                    {
                        path.AddEllipse(point.X - 5, point.Y - 5, 10, 10);
                        using (PathGradientBrush glowBrush = new PathGradientBrush(path))
                        {
                            glowBrush.CenterColor = Color.FromArgb(150, accentColor);
                            glowBrush.SurroundColors = new Color[] { Color.FromArgb(0, accentColor) };
                            g.FillPath(glowBrush, path);
                        }
                    }
                }
            }
        }
        
        private void CreatePieChart()
        {
            // 创建饼图面板
            Panel pieChartPanel = new Panel();
            pieChartPanel.Dock = DockStyle.Fill;
            pieChartPanel.BackColor = Color.Transparent;
            
            // 添加标题
            Label titleLabel = new Label();
            titleLabel.Text = "产品类型分布";
            titleLabel.Font = new Font("微软雅黑", 12, FontStyle.Bold);
            titleLabel.ForeColor = accentColor;
            titleLabel.AutoSize = true;
            titleLabel.Location = new Point(10, 10);
            
            // 创建图表区域
            Panel chartArea = new Panel();
            chartArea.Dock = DockStyle.Bottom;
            chartArea.Height = chartPanel2.Height - 40;
            chartArea.BackColor = Color.Transparent;
            chartArea.Paint += (sender, e) => DrawPieChart(e.Graphics, chartArea.ClientRectangle);
            
            // 添加控件到面板
            pieChartPanel.Controls.Add(titleLabel);
            pieChartPanel.Controls.Add(chartArea);
            
            // 添加到主面板
            chartPanel2.Controls.Add(pieChartPanel);
        }
        
        private void DrawPieChart(Graphics g, Rectangle bounds)
        {
            if (productDistribution.Count == 0) return;
            
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            
            // 计算总和
            int total = productDistribution.Values.Sum();
            if (total == 0) return;
            
            // 定义颜色 - 更科技感的配色
            Color[] colors = new Color[] 
            {
                Color.FromArgb(0, 150, 255),  // 亮蓝色
                Color.FromArgb(170, 0, 255),  // 紫色
                Color.FromArgb(50, 70, 100),  // 深蓝灰色
                Color.FromArgb(0, 210, 180)   // 青绿色
            };
            
            // 计算圆心和半径
            int centerX = bounds.Left + bounds.Width / 2;
            int centerY = bounds.Top + bounds.Height / 2;
            int radius = Math.Min(bounds.Width, bounds.Height) / 2 - 40;
            
            // 绘制饼图
            float startAngle = 0;
            int colorIndex = 0;
            
            foreach (var item in productDistribution)
            {
                float sweepAngle = (float)item.Value / total * 360;
                
                using (SolidBrush pieBrush = new SolidBrush(colors[colorIndex % colors.Length]))
                {
                    // 绘制扇形
                    g.FillPie(pieBrush, centerX - radius, centerY - radius, radius * 2, radius * 2, startAngle, sweepAngle);
                }
                
                // 添加高光效果
                using (GraphicsPath path = new GraphicsPath())
                {
                    path.AddPie(centerX - radius + 5, centerY - radius + 5, (radius - 5) * 2, (radius - 5) * 2, startAngle, sweepAngle);
                    using (PathGradientBrush highlightBrush = new PathGradientBrush(path))
                    {
                        highlightBrush.CenterColor = Color.FromArgb(100, 255, 255, 255);
                        highlightBrush.SurroundColors = new Color[] { Color.FromArgb(0, 255, 255, 255) };
                        g.FillPath(highlightBrush, path);
                    }
                }
                
                // 计算标签位置
                double midAngle = (startAngle + sweepAngle / 2) * Math.PI / 180;
                float labelX = centerX + (float)(Math.Cos(midAngle) * (radius + 20));
                float labelY = centerY + (float)(Math.Sin(midAngle) * (radius + 20));
                
                // 绘制标签
                string label = item.Key + ": " + Math.Round((float)item.Value / total * 100) + "%";
                SizeF textSize = g.MeasureString(label, new Font("Arial", 8));
                
                // 调整标签位置，避免超出边界
                if (labelX + textSize.Width > bounds.Right)
                    labelX = bounds.Right - textSize.Width;
                if (labelX < bounds.Left)
                    labelX = bounds.Left;
                    
                g.DrawString(label, new Font("Arial", 8), new SolidBrush(Color.FromArgb(220, 220, 240)), labelX, labelY);
                
                startAngle += sweepAngle;
                colorIndex++;
            }
        }
        
        private void CreateBarChart()
        {
            // 创建柱状图面板
            Panel barChartPanel = new Panel();
            barChartPanel.Dock = DockStyle.Fill;
            barChartPanel.BackColor = Color.Transparent;
            
            // 添加标题
            Label titleLabel = new Label();
            titleLabel.Text = "月度产量统计";
            titleLabel.Font = new Font("微软雅黑", 12, FontStyle.Bold);
            titleLabel.ForeColor = accentColor;
            titleLabel.AutoSize = true;
            titleLabel.Location = new Point(10, 10);
            
            // 创建图表区域
            Panel chartArea = new Panel();
            chartArea.Dock = DockStyle.Bottom;
            chartArea.Height = gaugePanel1.Height - 40;
            chartArea.BackColor = Color.Transparent;
            chartArea.Paint += (sender, e) => DrawBarChart(e.Graphics, chartArea.ClientRectangle);
            
            // 添加控件到面板
            barChartPanel.Controls.Add(titleLabel);
            barChartPanel.Controls.Add(chartArea);
            
            // 添加到主面板
            gaugePanel1.Controls.Add(barChartPanel);
        }
        
        private void DrawBarChart(Graphics g, Rectangle bounds)
        {
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            
            // 柱状图数据
            string[] months = { "1月", "2月", "3月", "4月", "5月", "6月" };
            int[] values = { 35, 42, 28, 45, 50, 38 };
            
            // 计算坐标
            int maxValue = values.Max() * 12 / 10; // 最大值上浮20%
            int padding = 30;
            int leftPadding = 40;
            int bottomPadding = 30;
            
            int graphWidth = bounds.Width - leftPadding - padding;
            int graphHeight = bounds.Height - padding - bottomPadding;
            
            int barCount = months.Length;
            int barWidth = (graphWidth / barCount) - 10;
            
            // 绘制坐标轴
            using (Pen axisPen = new Pen(Color.FromArgb(150, 150, 180), 1))
            {
                // Y轴
                g.DrawLine(axisPen, 
                    new Point(bounds.Left + leftPadding, bounds.Top + padding),
                    new Point(bounds.Left + leftPadding, bounds.Bottom - bottomPadding));
                    
                // X轴
                g.DrawLine(axisPen,
                    new Point(bounds.Left + leftPadding, bounds.Bottom - bottomPadding),
                    new Point(bounds.Right - padding, bounds.Bottom - bottomPadding));
            }
            
            // 绘制网格线
            using (Pen gridPen = new Pen(Color.FromArgb(80, 80, 120), 1))
            {
                gridPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                
                // 水平网格线
                int ySteps = 5;
                for (int i = 0; i <= ySteps; i++)
                {
                    int y = bounds.Bottom - bottomPadding - (i * graphHeight / ySteps);
                    g.DrawLine(gridPen,
                        new Point(bounds.Left + leftPadding, y),
                        new Point(bounds.Right - padding, y));
                        
                    // 绘制Y轴刻度
                    int value = maxValue * i / ySteps;
                    string valueText = value.ToString();
                    SizeF textSize = g.MeasureString(valueText, new Font("Arial", 8));
                    g.DrawString(valueText, new Font("Arial", 8), new SolidBrush(Color.FromArgb(200, 200, 220)),
                        new PointF(bounds.Left + leftPadding - textSize.Width - 5, y - textSize.Height / 2));
                }
            }
            
            // 绘制柱状图
            for (int i = 0; i < barCount; i++)
            {
                int barHeight = values[i] * graphHeight / maxValue;
                int barLeft = bounds.Left + leftPadding + i * (barWidth + 10) + 5;
                int barTop = bounds.Bottom - bottomPadding - barHeight;
                
                // 创建圆角矩形路径
                GraphicsPath barPath = new GraphicsPath();
                int cornerRadius = 5;
                barPath.AddArc(barLeft, barTop, cornerRadius * 2, cornerRadius * 2, 180, 90);
                barPath.AddArc(barLeft + barWidth - cornerRadius * 2, barTop, cornerRadius * 2, cornerRadius * 2, 270, 90);
                barPath.AddArc(barLeft + barWidth - cornerRadius * 2, barTop + barHeight - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 0, 90);
                barPath.AddArc(barLeft, barTop + barHeight - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 90, 90);
                barPath.CloseAllFigures();
                
                // 创建渐变画刷
                using (LinearGradientBrush barBrush = 
                    new LinearGradientBrush(
                        new Point(barLeft, barTop),
                        new Point(barLeft, bounds.Bottom - bottomPadding),
                        Color.FromArgb(0, 210, 255),
                        Color.FromArgb(0, 130, 210)))
                {
                    // 绘制柱子
                    g.FillPath(barBrush, barPath);
                    
                    // 添加高光效果
                    using (LinearGradientBrush highlightBrush = 
                        new LinearGradientBrush(
                            new Point(barLeft, barTop),
                            new Point(barLeft + barWidth, barTop),
                            Color.FromArgb(150, 255, 255, 255),
                            Color.FromArgb(30, 255, 255, 255)))
                    {
                        g.FillRectangle(highlightBrush, barLeft, barTop, barWidth, 10);
                    }
                }
                
                // 绘制数值
                string valueText = values[i].ToString();
                SizeF textSize = g.MeasureString(valueText, new Font("Arial", 8));
                g.DrawString(valueText, new Font("Arial", 8), new SolidBrush(Color.FromArgb(220, 220, 240)),
                    new PointF(barLeft + (barWidth - textSize.Width) / 2, barTop - textSize.Height - 2));
                
                // 绘制X轴标签
                string month = months[i];
                textSize = g.MeasureString(month, new Font("Arial", 8));
                g.DrawString(month, new Font("Arial", 8), new SolidBrush(Color.FromArgb(200, 200, 220)),
                    new PointF(barLeft + (barWidth - textSize.Width) / 2, bounds.Bottom - bottomPadding + 5));
            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            try
            {
                // 开始模拟数据
                timer1.Interval = 1000; // 1秒更新一次
                timer1.Start();
                simpleButton1.Enabled = false;
                simpleButton2.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("启动模拟数据时出错: " + ex.Message);
            }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            try
            {
                // 停止模拟数据
                timer1.Stop();
                simpleButton1.Enabled = true;
                simpleButton2.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("停止模拟数据时出错: " + ex.Message);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                // 更新数据
                UpdateData();
                
                // 刷新图表
                chartPanel1.Invalidate(true);
                chartPanel2.Invalidate(true);
                gaugePanel1.Invalidate(true);
                
                // 增加数据计数
                dataCount++;
            }
            catch (Exception ex)
            {
                timer1.Stop();
                MessageBox.Show("更新数据时出错: " + ex.Message);
                simpleButton1.Enabled = true;
                simpleButton2.Enabled = false;
            }
        }

        private void UpdateData()
        {
            // 生成随机数据
            double newValue = Math.Round(random.NextDouble() * 100, 2);
            productionData.Add(newValue);
            
            // 限制数据点数量
            if (productionData.Count > 10)
            {
                productionData.RemoveAt(0);
            }
            
            // 更新选中的产品类型数量
            if (productDistribution.ContainsKey(selectedProductType))
            {
                productDistribution[selectedProductType] += random.Next(1, 5);
            }
        }

        private void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                // 更新选中的产品类型
                if (comboBoxEdit1.SelectedItem != null)
                {
                    selectedProductType = comboBoxEdit1.SelectedItem.ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("选择产品类型时出错: " + ex.Message);
            }
        }
    }
}